/**
 * 
 */
package com.scpii.universal.service.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.googlecode.ehcache.annotations.Cacheable;
import com.googlecode.ehcache.annotations.TriggersRemove;
import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.dto.AppPageDto;
import com.scpii.universal.dto.AppPageViewDto;
import com.scpii.universal.dto.AttributeDto;
import com.scpii.universal.dto.ContentDto;
import com.scpii.universal.dto.ContentImgDtoForPru;
import com.scpii.universal.dto.PageInfoDto;
import com.scpii.universal.dto.PageNode;
import com.scpii.universal.dto.PageTree;
import com.scpii.universal.dto.SortColumnsDto;
import com.scpii.universal.dto.TypeDto;
import com.scpii.universal.dto.UserInfoDto;
import com.scpii.universal.dto.ViewAttributeDto;
import com.scpii.universal.hibernate.dao.AppIconDao;
import com.scpii.universal.hibernate.dao.AppPageDao;
import com.scpii.universal.hibernate.dao.AppPageViewDao;
import com.scpii.universal.hibernate.dao.AppViewCatelogRalationDao;
import com.scpii.universal.hibernate.dao.AppViewContentRalationDao;
import com.scpii.universal.hibernate.dao.AttributeDao;
import com.scpii.universal.hibernate.dao.BindContentAttributeDao;
import com.scpii.universal.hibernate.dao.CatelogDao;
import com.scpii.universal.hibernate.dao.DataSortDao;
import com.scpii.universal.hibernate.dao.ModuleStyleDao;
import com.scpii.universal.hibernate.dao.MoreContentDao;
import com.scpii.universal.hibernate.dao.PageNavigationDao;
import com.scpii.universal.hibernate.dao.TypeDao;
import com.scpii.universal.hibernate.dao.ViewContentAttributeDao;
import com.scpii.universal.hibernate.entity.AppPageTab;
import com.scpii.universal.hibernate.entity.AppPageViewTab;
import com.scpii.universal.hibernate.entity.AppViewCatelogRalationTab;
import com.scpii.universal.hibernate.entity.AppViewContentRalationTab;
import com.scpii.universal.hibernate.entity.AttributeTab;
import com.scpii.universal.hibernate.entity.BindContentAttributeTab;
import com.scpii.universal.hibernate.entity.CatelogTab;
import com.scpii.universal.hibernate.entity.ContentTab;
import com.scpii.universal.hibernate.entity.DataSortTab;
import com.scpii.universal.hibernate.entity.ModuleStyleTab;
import com.scpii.universal.hibernate.entity.MoreContentTab;
import com.scpii.universal.hibernate.entity.PageNavigationTab;
import com.scpii.universal.hibernate.entity.ViewContentAttributeTab;
import com.scpii.universal.service.AppContentService;
import com.scpii.universal.service.AppPageService;
import com.scpii.universal.service.ContentImgService;
import com.scpii.universal.service.ContentService;

/**
 * universalWeb
 * @author liuhj
 * 2012-7-14下午05:15:27
 */
@Service
public class AppPageServiceImpl extends BaseServiceImpl<AppPageTab, Integer> implements
		AppPageService {
	@Resource
	private AppPageDao appPageDao;
	@Resource
	private ModuleStyleDao moduleStyleDao;
	@Resource
	private AppPageViewDao appPageViewDao;
	@Resource
	private AppViewCatelogRalationDao appViewCatelogRalationDao;
	@Resource
	private CatelogDao catelogDao;
	@Resource
	private ViewContentAttributeDao viewContentAttributeDao;
	@Resource
	private AttributeDao attributeDao;
	@Resource
	private AppIconDao appIconDao;
	@Resource
	private PageNavigationDao pageNavigationDao;
	@Resource
	private AppViewContentRalationDao appViewContentRalationDao;
	@Resource
	private BindContentAttributeDao bindContentAttributeDao;
	@Resource
	private AppContentService appContentService;
	@Resource
	private ContentService contentService;
	@Resource
	private ContentImgService contentImgService;
	@Resource
	private MoreContentDao moreContentDao;
	@Resource
	private TypeDao typeDao;
	@Resource
	private DataSortDao dataSortDao;
	private static final String[] VIEW_PROPERTIES = { "intViewId" };
	private static final String[] CATELOG_PROPERTIES = { "intCateId", "intHasSubCate" };
	private static final String[] RELATION_POPERTIES = { "intViewCateId",
			"intCateId", "intResourceId", "intContentType" };
	private Log log = LogFactory.getLog(this.getClass());

	@Resource
	public void setBaseDao(AppPageDao appPageDao) {
		super.setBaseDao(appPageDao);
	}

	@Override
	public List<AppPageTab> getAllChildrenPageById(Integer id, String[] properties) {
		List<AppPageTab> lstChildren = appPageDao.getNextLevelChildren(id, properties);
		return recursivChildrenPage(lstChildren,null,properties);
	}
	
	/**
	 * 递归子节点
	 * @param lstAll
	 * @param temp
	 * @return
	 * @author liuhj
	 * 2012-7-14下午05:15:52
	 */
	private List<AppPageTab> recursivChildrenPage(List<AppPageTab> lstAll,List<AppPageTab> temp,String[] properties) {
		if (temp == null ) {
			temp = new ArrayList<AppPageTab>();
		}
		for (AppPageTab appPageTab : lstAll) {
			temp.add(appPageTab);
			List<AppPageTab> lstNextChildren = appPageDao
					.getNextLevelChildren(appPageTab.getIntResourceId(), properties);
			if (lstNextChildren != null && lstNextChildren.size() > 0) {
				recursivChildrenPage(lstNextChildren, temp,properties);
			}
		}
		return temp;
	}

	@Override
	public String generatePagesTree(int appId) {
		//根据导航获得所有的根页面
		List<AppPageDto> lstPages = appPageDao.getPagesByNavigation(appId);
		return populateTree(lstPages);
	}

	private String populateTree(List<AppPageDto> lstPages) {
		List<PageTree> subNodes = null;
		if (lstPages != null && lstPages.size() > 0) {
			PageNode parent = null;
			List<PageNode> tree = new ArrayList<PageNode>();
			for (AppPageDto appPageDto : lstPages) {
				//判断是否有子页面[除开详情页面]
				subNodes = appPageDao.getPageTreeByPageId(appPageDto
						.getIntResourceId());
				parent = new PageNode(
						appPageDto.getIntResourceId(),0,
						appPageDto.getVarTitleName(),0,
						(subNodes != null && subNodes.size() > 0) ? GenericConstants.NEXT_PAGE_CONTENT_TYPE_CATE
								: GenericConstants.NEXT_PAGE_CONTENT_TYPE_LIST,
						appPageDto.getIntNavigateType());
				tree.add(parent);
				findChildren(parent, subNodes);
			}
			JSONArray jsonSet = JSONArray.fromObject(tree);
			String result = "{\"pageTree\":"
					+ jsonSet.toString().replaceAll("\\[\\]", "\"-1\"") + "}";
			if(log.isDebugEnabled()){
				log.debug("页面树结构的json返回数据:" + result);
			}
			return result;

		}
		return null;
	}
	
	private void findChildren(PageNode parent, List<PageTree> subNodes) {
		PageNode node = null;
		for (int i = 0; i < subNodes.size(); i++) {
			PageTree page = subNodes.get(i);
			if (page.getParentPageId().intValue() == parent.getIntResourceId()
					.intValue()) {
				node = new PageNode(page.getIntResourceId(), page
						.getParentPageId(), page.getVarResourceName(), 1, page
						.getNextType(),GenericConstants.NAV_TYPE_COMMON);
				parent.addChild(node);
				if (page.getNextType().intValue() == GenericConstants.NEXT_PAGE_CONTENT_TYPE_CATE) {
					// 有子节点
					findChildren(node, subNodes);
				}
			}
		}
	}

	@Override
	public List<AppPageTab> getNextLevelChildren(Integer id, String[] properties) {
		return appPageDao.getNextLevelChildren(id, properties);
	}

	@Override
	public List<ModuleStyleTab> getAllModuleStyle() {
		String[] properties = {"intModuleStyleId","varModuleStyleName","varModuleImgUrl"};
		return moduleStyleDao.getAllModuleStyle(properties, 0);
	}

	@Override
	public List<ModuleStyleTab> getAllModuleDisplayStyle(int parentId) {
		String[] properties = {"intModuleStyleId","varModuleStyleName","varModuleImgUrl"};
		return moduleStyleDao.getAllModuleStyle(properties, parentId);
	}

	@Override
	public void updatePageModuleStyle(int pageId, int styleId) {
		StringBuffer hql = new StringBuffer("update AppPageTab a set ");
		hql.append("a.intThisModuleId=:intThisModuleId");
		Map<String, Object> argsMap = new HashMap<String, Object>();
		argsMap.put("intThisModuleId", styleId);//本级模版
		hql.append(",a.intNextModuleId=:intNextModuleId");
		argsMap.put("intNextModuleId", styleId);//下级模版
		hql.append(" where a.intResourceId=:intResourceId");
		argsMap.put("intResourceId", pageId);
		appPageDao.hqlOperation(hql.toString(), argsMap);
	}
	
	/**
	 * 更新页面标题信息
	 * @param page
	 * @author liuhj
	 * 2012-8-3下午03:10:20
	 */
	private void updatePageTitleInfo(AppPageTab page,UserInfoDto user) {
		if (page.getIntResourceId() == -1) {
			page.setDatUpdateDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			page.setIntAppId(user.getAppId());
			page.setIntEnterpId(user.getIntEnterpId());
			page.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
			page.setIntTitleIconId(page.getIntTitleIconId()==null?0:page.getIntTitleIconId());
			appPageDao.save(page);
			return;
		}
		if ("-1".equals(page.getVarTitleName())
				&& page.getIntTitleIconId() == -1) {
			return;
		}
		StringBuffer hql = new StringBuffer("update AppPageTab a set");
		Map<String, Object> argsMap = new HashMap<String, Object>();
		if (!"-1".equals(page.getVarTitleName())) {
			hql.append(" a.varTitleName=:varTitleName,");
			argsMap.put("varTitleName", page.getVarTitleName());
		}
		if (page.getIntTitleIconId() != -1) {
			hql.append(" a.intTitleIconId=:intTitleIconId,");
			argsMap.put("intTitleIconId", page.getIntTitleIconId());
		}
		hql.deleteCharAt(hql.lastIndexOf(","));
		hql.append(" where a.intResourceId=:intResourceId");
		argsMap.put("intResourceId", page.getIntResourceId());
		appPageDao.hqlOperation(hql.toString(), argsMap);
	}

	@Override
	@TriggersRemove(cacheName=GenericConstants.CATELOG_EHCACHE,removeAll=true)
	public Integer saveOrUpdatePage(String jsonData, UserInfoDto user) {
		JSONObject json = JSONObject.fromObject(jsonData);
		if(log.isDebugEnabled()){
			log.debug("保存页面的json请求数据:"+json.toString());
		}
		//更新页面信息
		AppPageTab page = (AppPageTab) JSONObject.toBean(json
				.getJSONObject("pageInfo"), AppPageTab.class);
		updatePageTitleInfo(page,user);
		Integer result = page.getIntResourceId();
		JSONArray ja = JSONArray.fromObject(json.get("views"));
		int size = ja.size();
		for (int i = 0; i < size; i++) {
			JSONObject jo = JSONObject.fromObject(ja.get(i));
			//遍历视图
			AppPageViewTab view = (AppPageViewTab) JSONObject.toBean(jo
					.getJSONObject("viewInfo"), AppPageViewTab.class);
			view.setVarViewConfig(jo.getJSONObject("viewInfo").getString("varViewConfig"));
			//获得视图绑定类型
			int bindingType = view.getIntViewBindDatatype();
			if (bindingType == GenericConstants.BINDING_DATA_TYPE_CONTENT) {
				//绑定的为内容
				saveOrUpdateContentBinding(jo, page, view);
			} else if (bindingType == GenericConstants.BINDING_DATA_TYPE_CATELOG) {
				//绑定的为分类
				saveOrUpdateCatelogBinding(jo, view, page, user);
			} else if (bindingType == GenericConstants.BINDING_DATA_TYPE_FUNCTION) {
				//绑定的为功能
				saveOrUpdateMoreBinding(jo, view, page, user);
			}
		}
		return result;
	}
	
	
	/**
	 * 保存视图分类绑定
	 * @param jo
	 * @param view
	 * @param page
	 * @param user
	 * @author liuhj
	 * 2012-8-10下午10:36:35
	 */
	private void saveOrUpdateCatelogBinding(JSONObject jo, AppPageViewTab view,
			AppPageTab page, UserInfoDto user) {
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		JSONArray catelogs = jo.getJSONArray("catelogViewInfo");
		/*if (catelogs.size() <= 0) {
			//视图里没有分类被引用
			return;
		}*/
		view.setDatUpdateDatetime(date);
		view.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		view.setIntViewBindDatatype(GenericConstants.BINDING_DATA_TYPE_CATELOG);
		int viewId = view.getIntViewId();
		//视图属性对应
		JSONArray attributes = jo.getJSONArray("viewAttributeInfo");
		if (viewId == -1) {
			//保存视图
			view.setIntResourceId(page.getIntResourceId());
			viewId = appPageViewDao.save(view);
			saveViewAttributeMapping(attributes, viewId);
		} else {
			//更新视图
			appPageViewDao.update(view);
			saveOrUpdViewAttributeMapping(attributes, viewId);
		}
		
		//视图对应的分类
		for (int j = 0; j < catelogs.size(); j++) {
			JSONObject catelog = JSONObject.fromObject(catelogs.get(j));
			AppViewCatelogRalationTab paramRelation = (AppViewCatelogRalationTab) JSONObject
					.toBean(catelog, AppViewCatelogRalationTab.class);
			int cateId = paramRelation.getIntCateId();
			int relationId = paramRelation.getIntViewCateId();
			if (relationId == -1) {
				//新增视图分类关联
				if (!appViewCatelogRalationDao.checkIfExistRelation(viewId, cateId)) {
					log.info("校验视图" + viewId + "分类" + cateId
							+ "的关联是否存在：不存在");
					//先校验视图关联是否存在，保存视图分类关联
					AppViewCatelogRalationTab relation = this.saveCatelogViewRelation(cateId, viewId, paramRelation.getIntSortOrder());
					//递归子分类为其创建页面
					int moduleStyleId = view.getIntModuleStyleId();
					recursivCreatePages(attributes, relation, cateId, user,view);
				} else {
					log.info("视图" + viewId + "分类" + cateId
							+ "的关联已经存在，同一视图下相同的分类只能对应一次!");
				}
			} else {
				//更新视图分类关联(删除原有关联，建立新的视图分类关联)
				AppViewCatelogRalationTab relation = appViewCatelogRalationDao.get(relationId);
				if (cateId != relation.getIntCateId() ) {
					//更新关联的分类ID
					relation.setIntCateId(cateId);//在recursivCreatePages()方法update
					relation.setIntSortOrder(paramRelation.getIntSortOrder());
					//删除视图分类关联跳转页面的内容
					deleteRelationByViewCate(paramRelation);
					//递归子分类为其创建页面
					recursivCreatePages(attributes, relation, cateId,
							user, view);
				} else {
					//只更新order
					updateCateRefOrder(paramRelation);
				}
			}
		}
		//排序字段处理
		int isContentList = jo.getInt("isContentList");
		if (isContentList == GenericConstants.OPTION_YES) {
			saveOrUpdateSortColumns(jo, viewId);
		}
	}
	
	/**
	 * 根据半风格获取全风格
	 * @param styleId
	 * @return
	 * @author liuhj
	 * 2012-8-21下午04:49:59
	 */
	private int getStyleId(int styleId) {
		switch (styleId) {
		case GenericConstants.LIST_STYLE_HALF_1:
			return GenericConstants.LIST_STYLE_FULL_1;
		case GenericConstants.LIST_STYLE_HALF_2:
			return GenericConstants.LIST_STYLE_FULL_2;
		case GenericConstants.LIST_STYLE_HALF_3:
			return GenericConstants.LIST_STYLE_FULL_3;
		case GenericConstants.GRID_STYLE_HALF_1:
			return GenericConstants.GRID_STYLE_FULL_2;
		case GenericConstants.GRID_STYLE_HALF_2:
			return GenericConstants.GRID_STYLE_FULL_1;
		case GenericConstants.GALLERY_STYLE_HALF_1:
			return GenericConstants.GALLERY_STYLE_FULL_1;
		case GenericConstants.GALLERY_STYLE_HALF_2:
			return GenericConstants.GALLERY_STYLE_FULL_2;
		case GenericConstants.GRID_STYLE_HALF_3:
			return GenericConstants.GRID_STYLE_FULL_3;
		default:
			return styleId;
		}
	}
	
	/**
	 * 保存或更新视图属性对应
	 * @param attribute
	 * @param viewId
	 * @author liuhj
	 * 2012-7-28下午02:48:06
	 */
	private void saveOrUpdViewAttributeMapping(JSONArray attributes,int viewId) {
		for (int k = 0; k < attributes.size(); k++) {
			JSONObject attrObj = JSONObject.fromObject(attributes.get(k));
			ViewContentAttributeTab attribute = (ViewContentAttributeTab) JSONObject
					.toBean(attrObj, ViewContentAttributeTab.class);
			if (attribute.getIntViewAttriId() == -1 && attribute.getIntAttriOrder() > 0
					&& attribute.getIntAttriId() > 0) {
				// 保存
				attribute.setDatUpdateDatetime(new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss").format(new Date()));
				attribute.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
				attribute.setIntViewId(viewId);
				viewContentAttributeDao.save(attribute);
				continue;
			} 
			if (attribute.getIntViewAttriId() > 0 && attribute.getIntAttriOrder() == -1) {
				// 删除
				StringBuffer hql = new StringBuffer("update ViewContentAttributeTab v");
				hql.append(" set v.intDeleteSign=:intDeleteSign");
				hql.append(" where v.intViewAttriId=:intViewAttriId");
				HashMap<String,Object> args = new HashMap<String,Object>();
				args.put("intDeleteSign", GenericConstants.DELETE_SIGN_DELETED);
				args.put("intViewAttriId", attribute.getIntViewAttriId());
				viewContentAttributeDao.hqlOperation(hql.toString(), args);
				continue;
			} 
			if (attribute.getIntViewAttriId() > 0 && attribute.getIntAttriOrder() > 0) {
				// 更新
				StringBuffer hql = new StringBuffer("update ViewContentAttributeTab v");
				hql.append(" set v.intAttriId=:intAttriId,v.intAttriOrder=:intAttriOrder");
				hql.append(" where v.intViewAttriId=:intViewAttriId");
				HashMap<String,Object> args = new HashMap<String,Object>();
				args.put("intAttriId", attribute.getIntAttriId());
				args.put("intAttriOrder", attribute.getIntAttriOrder());
				args.put("intViewAttriId", attribute.getIntViewAttriId());
				viewContentAttributeDao.hqlOperation(hql.toString(), args);
			}
		}
	}
	
	/**
	 * 保存视图属性对应
	 * @param attributes
	 * @param viewId
	 * @author liuhj
	 * 2012-8-1下午06:35:10
	 */
	private void saveViewAttributeMapping(JSONArray attributes,int viewId) {
		for (int k = 0; k < attributes.size(); k++) {
			JSONObject attrObj = JSONObject.fromObject(attributes.get(k));
			ViewContentAttributeTab attribute = (ViewContentAttributeTab) JSONObject
					.toBean(attrObj, ViewContentAttributeTab.class);
			if (attribute.getIntAttriId() <= 0
					|| attribute.getIntAttriOrder() <= 0)
				continue;
			attribute.setDatUpdateDatetime(new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss").format(new Date()));
			attribute.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
			attribute.setIntViewId(viewId);
			viewContentAttributeDao.save(attribute);
		}
	}
	
	/**
	 * 删除跳转页面，视图，视图分类关联
	 * @param relation
	 * @param viewId
	 * @author liuhj
	 * 2012-7-26上午10:08:25
	 */
	private void deleteRelationByViewCate(AppViewCatelogRalationTab relation) {
		if ( relation.getIntResourceId() > 0 ) {
			//获取跳转页面的所有视图
			List<AppPageViewTab> view = appPageViewDao.getViewsInfoByPageId(
					relation.getIntResourceId(), VIEW_PROPERTIES, false);
			//删除跳转页面
			appPageDao.delete(relation.getIntResourceId());
			for (AppPageViewTab appPageViewTab : view) {
				//删除跳转页面的视图
				appPageViewDao.delete(appPageViewTab.getIntViewId());
				if (relation.getIntContentType() == GenericConstants.NEXT_PAGE_CONTENT_TYPE_LIST) {
					//跳转页面的类型为列表,删除视图内容属性
					viewContentAttributeDao.deleteByViewId(appPageViewTab.getIntViewId());
				} else {
					viewContentAttributeDao.deleteByViewId(appPageViewTab.getIntViewId());
					List<AppViewCatelogRalationTab> relations = appViewCatelogRalationDao
						.getRelationsByViewId(appPageViewTab.getIntViewId(),RELATION_POPERTIES);
					//删除跳转页面的视图分类关联
					appViewCatelogRalationDao.deleteRelationsByViewId(appPageViewTab.getIntViewId());
					for (AppViewCatelogRalationTab appViewCatelogRalationTab : relations) {
						deleteRelationByViewCate(appViewCatelogRalationTab);
					}
				}
			}
		}
	}
	
	/**
	 * 递归子分类为其创建页面
	 * @param cateId
	 * @param user
	 * @param intModuleStyleId
	 * @author liuhj
	 * 2012-7-26上午12:01:40
	 */
	private void recursivCreatePages(JSONArray attributes, AppViewCatelogRalationTab relation,
			int cateId, UserInfoDto user, AppPageViewTab pView) {
		List<CatelogTab> catelogs = catelogDao.getNextLevelChildren(cateId,CATELOG_PROPERTIES);
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		//是否为分类最后一级,如果是将创建页面,视图,不创建视图分类关联
		boolean isLastLeaf = (catelogs != null && catelogs.size() > 0) ? false : true;
		//生成子页面
		AppPageTab page = new AppPageTab();
		page.setDatUpdateDatetime(date);
		page.setIntAppId(user.getAppId());
		page.setIntEnterpId(user.getIntEnterpId());
		page.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		page.setIntTitleIconId(0);
		//为页面生成默认的title名[上级分类的名字]
		page.setVarTitleName(catelogDao.getCatelogInfoById(cateId,
				new String[] { "intCateId", "varCateName" }).getVarCateName());
		Integer pageId = appPageDao.save(page);
		//更新上级视图分类关联
		relation.setIntResourceId(pageId);
		if (!isLastLeaf) {
			relation.setIntContentType(GenericConstants.NEXT_PAGE_CONTENT_TYPE_CATE);
		}
		appViewCatelogRalationDao.update(relation);
		//生成页面视图，默认只一个
		AppPageViewTab view = new AppPageViewTab();
		view.setDatUpdateDatetime(date);
		view.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		view.setIntModuleStyleId(pView.getIntModuleStyleId());//视图模版
		view.setIntResourceId(pageId);//所属页面
		view.setIntViewOrder(1);//顺序
		view.setIntViewBindDatatype(GenericConstants.BINDING_DATA_TYPE_CATELOG);//绑定数据类型
		view.setVarViewConfig(pView.getVarViewConfig());
		Integer viewId = appPageViewDao.save(view);
		if (!isLastLeaf) {
			//视图属性对应
			this.saveViewAttributeMapping(attributes, viewId);
			for (CatelogTab catelogTab : catelogs) {
				//生成视图分类关联
				AppViewCatelogRalationTab rel = this.saveCatelogViewRelation(catelogTab.getIntCateId(), viewId, 0);
				//递归
				recursivCreatePages(attributes, rel, catelogTab
						.getIntCateId(), user, pView);
			}
		}
	}
	
	/**
	 * 保存视图分类关联
	 * @param cateId
	 * @param viewId
	 * @param order
	 * @return
	 * @author liuhj
	 * 2012-7-24下午05:25:32
	 */
	private AppViewCatelogRalationTab saveCatelogViewRelation(int cateId,int viewId, int order) {
		AppViewCatelogRalationTab relation = new AppViewCatelogRalationTab();
		relation.setIntCateId(cateId);
		relation.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		relation.setIntResourceId(0);//跳转页面默认0
		relation.setDatUpdateDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		relation.setIntViewId(viewId);
		relation.setIntContentType(GenericConstants.NEXT_PAGE_CONTENT_TYPE_LIST);
		relation.setIntSortOrder(order);
		appViewCatelogRalationDao.save(relation);
		return relation;
	}

	@Override
	@TriggersRemove(cacheName=GenericConstants.CATELOG_EHCACHE,removeAll=true)
	public void deleteViewCateRelation(AppViewCatelogRalationTab relation) {
		//删除视图分类关联
		appViewCatelogRalationDao.delete(relation.getIntViewCateId());
		//删除跳转页面相关
		this.deleteRelationByViewCate(relation);
	}
	
	@Override
	@TriggersRemove(cacheName=GenericConstants.CATELOG_EHCACHE,removeAll=true)
	public void deleteView(int viewId) {
		AppPageViewTab view = appPageViewDao.get(viewId);
		if (view.getIntViewBindDatatype() == GenericConstants.BINDING_DATA_TYPE_FUNCTION) {
			//删除功能
			moreContentDao.deleteMoreContentByViewId(viewId);
		} else {
			List<AppViewCatelogRalationTab> relations = appViewCatelogRalationDao
				.getRelationsByViewId(viewId,RELATION_POPERTIES);
			for (AppViewCatelogRalationTab appViewCatelogRalationTab : relations) {
				//删除视图分类对应
				this.deleteViewCateRelation(appViewCatelogRalationTab);
			}
			//删除视图属性对应
			viewContentAttributeDao.deleteByViewId(viewId);
		}
		//删除视图
		appPageViewDao.delete(viewId);
	}

	@Override
	@Cacheable(cacheName=GenericConstants.CATELOG_EHCACHE)
	public String generatePageContentById(int pageId, int isFirstPage, int isContentListPage, int isMorePage) {
		JSONObject datas = new JSONObject();
		//获得页面信息
		AppPageTab page = appPageDao.getPageInfoById(pageId, new String[] {
				"intResourceId", "varTitleName", "intTitleIconId" });
		PageInfoDto pageDto = new PageInfoDto();
		BeanUtils.copyProperties(page, pageDto);
		if (page.getIntTitleIconId() != null) {
			pageDto.setVarIconUrl(appIconDao.getIconUrlById(page.getIntTitleIconId()));
		}
		if (isFirstPage == 0) {
			//根页面不显示标题名称
			pageDto.setVarTitleName("-1");
		}
		datas.put("pageInfo", pageDto);
		//获得页面视图信息
		String[] viewPro = { "intViewId", "intModuleStyleId", "intResourceId",
				"varViewName", "intViewOrder", "intViewBindDatatype", "varViewConfig" };
		List<AppPageViewTab> views = appPageViewDao.getViewsInfoByPageId(pageId, viewPro, true);
		if (views == null || views.size() <= 0) {
			datas.put("content", new JSONArray());
			if(log.isDebugEnabled()){
				log.debug("根据页面ID:"+pageId+"获取页面内容的json返回数据:"+datas.toString());
			}
			return datas.toString();
		}
		List<Object> jsonView = new ArrayList<Object>();
		if (isMorePage == GenericConstants.NAV_TYPE_MORE) {
			//该页面为更多页面
			populateViewMoreJson(jsonView,views,page.getIntResourceId());
		} else {
			for (AppPageViewTab appPageViewTab : views) {
				Map<String,Object> map = new HashMap<String,Object>();
				AppPageViewDto viewDto = new AppPageViewDto();
				BeanUtils.copyProperties(appPageViewTab, viewDto);
				viewDto.setIsContentList(isContentListPage);
				map.put("viewInfo", viewDto);
				int bindType = appPageViewTab.getIntViewBindDatatype();
				if ( bindType == GenericConstants.BINDING_DATA_TYPE_CONTENT) {
					// 视图绑定的内容
					map.put("viewAttributeInfo", new ArrayList<ViewAttributeDto>());
					populateViewContJson(map, appPageViewTab.getIntViewId(), viewDto);
				} else if ( bindType == GenericConstants.BINDING_DATA_TYPE_CATELOG) {
					// 视图绑定的分类
					populateViewCateJson(map, isContentListPage, appPageViewTab
							.getIntViewId(), pageId);
				} else if (bindType == GenericConstants.BINDING_DATA_TYPE_FUNCTION) {
					map.put("moreContents", moreContentDao.getAllMoreContentById(
							pageId, appPageViewTab.getIntViewId()));
				}
				jsonView.add(map);
			}
		}
		datas.put("content", JSONArray.fromObject(jsonView));
		if(log.isDebugEnabled()){
			log.debug("根据页面ID:"+pageId+"获取页面内容的json返回数据:"+datas.toString());
		}
		return datas.toString();
	}
	
	/**
	 * 封装更多页面视图内的JSON数据
	 * @param jsonView
	 * @param views
	 * @author liuhj
	 * 2012-8-13下午07:59:36
	 */
	private void populateViewMoreJson(List<Object> jsonView,
			List<AppPageViewTab> views, int pageId) {
		for (AppPageViewTab appPageViewTab : views) {
			Map<String, Object> map = new HashMap<String, Object>();
			AppPageViewDto viewDto = new AppPageViewDto();
			BeanUtils.copyProperties(appPageViewTab, viewDto);
			viewDto.setIsContentList(0);
			map.put("viewInfo", viewDto);
			map.put("moreContents", moreContentDao.getAllMoreContentById(
					pageId, appPageViewTab.getIntViewId()));
			jsonView.add(map);
		}
	}
	
	/**
	 * 封装视图内绑定为内容的JSON数据
	 * @param map
	 * @param viewId
	 * @param viewDto
	 * @author liuhj
	 * 2012-8-11下午06:34:27
	 */
	private void populateViewContJson(Map<String, Object> map, int viewId, AppPageViewDto viewDto) {
		List<AppViewContentRalationTab> lstContentRelation = appViewContentRalationDao
				.getRelationsByViewId(viewId, new String[] { "intViewContId",
						"intContentId" ,"intBindType" });
		JSONArray arrayContents = new JSONArray();
		JSONObject contentDatas = null;
		if (lstContentRelation != null && lstContentRelation.size() > 0) {
			if(lstContentRelation.get(0).getIntBindType() == GenericConstants.ISBINDLISTDIRECTLY_YES) {
				//绑定的为分类下的内容列表
				contentDatas = new JSONObject();
				AppViewContentRalationTab viewContRel = lstContentRelation.get(0);
				contentDatas.put("intViewContId", viewContRel.getIntViewContId());
				contentDatas.put("intCateId", viewContRel.getIntContentId());
				viewDto.setIntBindType(GenericConstants.ISBINDLISTDIRECTLY_YES);
				// 封装内容绑定的属性json
				contentDatas.put("bindingAttrs", bindContentAttributeDao
						.getBindContAttrsByViewContId(viewContRel.getIntViewContId()));
				//封装内容
				//查询1页6条记录
				List<ContentTab> contents = appContentService
						.getContentIdsByCateId(viewContRel.getIntContentId(), 1,6);
				// 封装内容的json数据
				JSONObject contentsJson = null;
				for (ContentTab contentTab : contents) {
					contentsJson = new JSONObject();
					boolean result = populateContentData(contentsJson, contentTab.getIntContentId());
					if (result) 
						arrayContents.add(contentsJson);
				}
				contentDatas.put("contentList", arrayContents);
				map.put("bindingCatelogList", contentDatas);
			} else {
				//绑定的为单个内容
				viewDto.setIntBindType(GenericConstants.ISBINDLISTDIRECTLY_NO);
				for (AppViewContentRalationTab appViewContentRalationTab : lstContentRelation) {
					// 封装内容的json数据
					contentDatas = new JSONObject();
					boolean result = populateContentData(contentDatas,
							appViewContentRalationTab.getIntContentId());
					if (result) {
						int viewContId = appViewContentRalationTab.getIntViewContId();
						contentDatas.put("intViewContId", viewContId);
						// 封装内容绑定的属性json
						contentDatas.put("bindingAttrs", bindContentAttributeDao
								.getBindContAttrsByViewContId(viewContId));
						arrayContents.add(contentDatas);
					}
					
				}
				map.put("bindingContents", arrayContents);
			}
		} else {
			map.put("bindingContents", arrayContents);
			map.put("bindingCatelogList", arrayContents);
		}
	}
	
	/**
	 * 封装视图内绑定为分类的JSON数据
	 * @param map
	 * @param isContentListPage
	 * @param viewId
	 * @param pageId
	 * @author liuhj
	 * 2012-8-11下午06:26:59
	 */
	private void populateViewCateJson(Map<String, Object> map,
			int isContentListPage, int viewId, int pageId) {
		//视图属性对应
		List<ViewAttributeDto> viewAttributes = viewContentAttributeDao
				.getViewContentAttributes(viewId);
		map.put("viewAttributeInfo", viewAttributes);
		if (isContentListPage == GenericConstants.NEXT_PAGE_CONTENT_TYPE_LIST) {
			//该视图内为内容列表，查询内容
			//查询分类ID
			AppViewCatelogRalationTab catRel = appViewCatelogRalationDao
					.getRelationByPageId(pageId, new String[] {"intViewCateId", "intCateId" });
			if (catRel == null) {
				return;
			}
			int cateId = catRel.getIntCateId();
			//查询1页6条记录
			List<ContentTab> contents = appContentService
					.getContentIdsByCateId(cateId, 1,6);
			JSONArray arrayContents = new JSONArray();
			JSONObject contentDatas = null;
			//封装内容的json数据
			for (ContentTab contentTab : contents) {
				contentDatas = new JSONObject();
				boolean result = populateContentData(contentDatas, contentTab.getIntContentId());
				if (result)
					arrayContents.add(contentDatas);
			}
			map.put("contentList", arrayContents);
		} else {
			//该视图内为分类
			// 获得页面视图里的分类对应
			map.put("catelogViewInfo", appViewCatelogRalationDao
					.getRelationsByViewId(viewId));
		}
	}
	
	/**
	 * 封装内容的基本信息，扩展属性信息，图片信息
	 * @param datas
	 * @param intContentId
	 * @return
	 * @throws IOException
	 * @author liuhj
	 * 2012-8-9下午05:58:50
	 */
	private boolean populateContentData(JSONObject datas,int intContentId) {
		// 内容信息
		ContentTab content = contentService.get(intContentId );
		if (content == null) {
			return false;
		}
		ContentDto contentDto = new ContentDto();
		BeanUtils.copyProperties(content, contentDto);
		// 属性信息
		List<AttributeDto> lstAttr = appContentService.getAttribyteById(intContentId);
		if (lstAttr == null){
			lstAttr = new ArrayList<AttributeDto>();
		}
		//封装添加时间属性
		AttributeDto attrTime = new AttributeDto();
		attrTime.setIntAttriId(4);
		attrTime.setVarAttriName("添加时间");
		attrTime.setIntContentId(intContentId);
		attrTime.setVarAttriValue(content.getDatAddDatetime());
		lstAttr.add(attrTime);
		// 图片信息
		List<ContentImgDtoForPru> lstImg = contentImgService.getImgsInfotById(intContentId);
		datas.put("contentInfo", contentDto);
		datas.put("attrInfo", lstAttr);
		datas.put("imgInfo", lstImg);
		return true;
	}

	@Override
	public List<AttributeTab> getAttributesByCateId(CatelogTab catelog) {
		String[] properties = { "intAttriId", "varAttriName"};
		return attributeDao.getAttributesByCateId("(0)", properties);
	}

	@Override
	@TriggersRemove(cacheName=GenericConstants.CATELOG_EHCACHE,removeAll=true)
	public void deleteNavigation(int navId) {
		PageNavigationTab nav = pageNavigationDao.getNavInfoById(navId,
				new String[] { "intResourceId" });
		pageNavigationDao.delete(navId);
		this.deletePage(nav.getIntResourceId());
	}
	
	/**
	 * 保存视图内容绑定
	 * @param jo
	 * @param page
	 * @param view
	 * @author liuhj
	 * 2012-8-10下午10:37:03
	 */
	private void saveOrUpdateContentBinding(JSONObject jo, AppPageTab page,
			AppPageViewTab view) {
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		JSONArray bindContents = jo.getJSONArray("contentBind");
		if (bindContents.size() <= 0) {
			//视图里没有内容被引用
			return;
		}
		view.setDatUpdateDatetime(date);
		view.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		view.setIntViewBindDatatype(GenericConstants.BINDING_DATA_TYPE_CONTENT);
		int viewId = view.getIntViewId();
		if (viewId == -1) {
			//保存视图
			view.setIntResourceId(page.getIntResourceId());
			viewId = appPageViewDao.save(view);
		} else {
			//更新视图
			appPageViewDao.update(view);
		}
		
		//视图对应的内容
		for (int j = 0; j < bindContents.size(); j++) {
			JSONObject bind = JSONObject.fromObject(bindContents.get(j));
			JSONObject content = bind.getJSONObject("contentViewInfo");
			JSONArray attributes = bind.getJSONArray("contentAttrInfo");
			AppViewContentRalationTab contentRelation = (AppViewContentRalationTab) JSONObject
					.toBean(content, AppViewContentRalationTab.class);
			int contentId = contentRelation.getIntContentId();
			int relationId = contentRelation.getIntViewContId();
			if (contentId == -1)
				continue;
			if (relationId == -1 && contentId != -1) {
				//检测该视图是否被绑定了分类下的内容列表
				if (checkIfExistSameRel(viewId,contentRelation.getIntBindType()))
					continue;
				//新增视图内容关联
				contentRelation.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
				contentRelation.setDatUpdateDatetime(date);
				contentRelation.setIntViewId(viewId);
				relationId = appViewContentRalationDao.save(contentRelation);
				//新增内容属性对应
				saveContentAttributeMapping(attributes, relationId);
			} else {
				//查询原绑定的内容ID
				int beforeBindContId = appViewContentRalationDao.getRelationInfoById(
								relationId,new String[] { "intViewContId", "intContentId" }).getIntContentId();
				if (beforeBindContId == contentId) {
					updateContRefOrder(contentRelation);
					// 新绑定的内容ID没有变化,只修改绑定属性
					saveOrUpdContAttributeMapping(attributes, relationId);
				} else {
					//更新视图内容关联
					updateViewContRef(attributes, contentRelation);
				}
			}
			if (contentRelation.getIntBindType() == GenericConstants.ISBINDLISTDIRECTLY_YES) {
				saveOrUpdateSortColumns(jo, viewId);
			}
		}
	}

	/**
	 * 排序字段处理
	 * @author Taylor
	 * 2012-11-21 上午10:35:03
	 * @param jo
	 * @param intViewId
	 */
	private void saveOrUpdateSortColumns(JSONObject jo,
			int intViewId) {
		JSONArray sortColumns = jo.getJSONArray("sortColumns");
		dataSortDao.delSelectedSortCols(intViewId);
		for (int i = 0; i < sortColumns.size(); i++) {
			SortColumnsDto sortColumnsDto = (SortColumnsDto) JSONObject
					.toBean(JSONObject.fromObject(sortColumns.get(i)),
							SortColumnsDto.class);
			DataSortTab dataSortTab  = new DataSortTab();
			dataSortTab.setIntColumnOrder(sortColumnsDto.getIntColumnOrder());
			dataSortTab.setIntIsAttr(sortColumnsDto.getIntIsAttr());
			dataSortTab.setIntSortColumnId(sortColumnsDto.getIntSortId());
			dataSortTab.setIntSortRule(sortColumnsDto.getIntSortRule());
			dataSortTab.setIntViewId(intViewId);
			dataSortTab.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
			dataSortTab.setIntIsShowInClient(GenericConstants.OPTION_NO);
			dataSortDao.save(dataSortTab);
		}
	}

	/**
	 * 检测视图内是否已经绑定了分类下的内容列表
	 * @author Taylor
	 * 2012-11-22 上午09:59:09
	 * @param viewId
	 * @param bindType
	 * @return
	 * boolean
	 */
	private boolean checkIfExistSameRel(int viewId,
			int bindType) {
		if (bindType==GenericConstants.ISBINDLISTDIRECTLY_YES){
			StringBuffer hql = new StringBuffer("select new AppViewContentRalationTab(a.intViewContId)");
			hql.append(" from AppViewContentRalationTab a");
			hql.append(" where a.intDeleteSign=:intDeleteSign");
			hql.append(" and a.intBindType=:intBindType");
			hql.append(" and a.intViewId=:intViewId");
			Map<String, Object> argsMap = new HashMap<String, Object>();
			argsMap.put("intDeleteSign", GenericConstants.DELETE_SIGN_EXIST);
			argsMap.put("intBindType", GenericConstants.ISBINDLISTDIRECTLY_YES);
			argsMap.put("intViewId", viewId);
			List<AppViewContentRalationTab> existRels = appViewContentRalationDao.hqlGetList(hql.toString(), argsMap);
			if (existRels != null && existRels.size() > 0) {
				log.warn("视图"+viewId+"已经绑定了分类下的内容列表，不能再绑定!");
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 更新内容绑定关系的ORDER
	 * @author Taylor
	 * 2012-11-19 下午02:30:20
	 * @param contentRelation
	 * void
	 */
	private void updateContRefOrder(AppViewContentRalationTab contentRelation) {
		StringBuffer hql = new StringBuffer("update AppViewContentRalationTab a set ");
		hql.append("a.intSortOrder=:intSortOrder");
		Map<String, Object> argsMap = new HashMap<String, Object>();
		argsMap.put("intSortOrder", contentRelation.getIntSortOrder());
		hql.append(" where a.intViewContId=:intViewContId");
		argsMap.put("intViewContId", contentRelation.getIntViewContId());
		appViewContentRalationDao.hqlOperation(hql.toString(), argsMap);
	}
	
	/**
	 * 更新分类绑定关系的ORDER
	 * @author Taylor
	 * 2012-11-19 下午02:30:20
	 * @param paramRelation
	 * void
	 */
	private void updateCateRefOrder(AppViewCatelogRalationTab paramRelation) {
		StringBuffer hql = new StringBuffer("update AppViewCatelogRalationTab a set ");
		hql.append("a.intSortOrder=:intSortOrder");
		Map<String, Object> argsMap = new HashMap<String, Object>();
		argsMap.put("intSortOrder", paramRelation.getIntSortOrder());
		hql.append(" where a.intViewCateId=:intViewCateId");
		argsMap.put("intViewCateId", paramRelation.getIntViewCateId());
		appViewCatelogRalationDao.hqlOperation(hql.toString(), argsMap);
	}

	/**
	 * 更新视图内容关联
	 * @author Taylor
	 * 2012-11-22 上午09:28:57
	 * @param attributes
	 * @param contentRelation
	 */
	private void updateViewContRef(JSONArray attributes, AppViewContentRalationTab contentRelation) {
		StringBuffer hql = new StringBuffer("update AppViewContentRalationTab a set ");
		hql.append("a.intContentId=:intContentId");
		hql.append(",a.intSortOrder=:intSortOrder");
		Map<String, Object> argsMap = new HashMap<String, Object>();
		argsMap.put("intContentId", contentRelation.getIntContentId());
		argsMap.put("intSortOrder", contentRelation.getIntSortOrder());
		hql.append(" where a.intViewContId=:intViewContId");
		argsMap.put("intViewContId", contentRelation.getIntViewContId());
		appViewContentRalationDao.hqlOperation(hql.toString(), argsMap);
		//删除原有绑定属性
		bindContentAttributeDao.delete(contentRelation.getIntViewContId());
		//重新绑定属性
		saveContentAttributeMapping(attributes, contentRelation.getIntViewContId());
	}
	
	
	/**
	 * 保存内容属性对应
	 * @param attributes
	 * @param viewId
	 * @author liuhj
	 * 2012-8-1下午06:35:10
	 */
	private void saveContentAttributeMapping(JSONArray attributes,int intViewContId) {
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		for (int i = 0; i < attributes.size(); i++) {
			JSONObject attrObj = JSONObject.fromObject(attributes.get(i));
			if (attrObj == null) 
				continue;
			BindContentAttributeTab bindContent = (BindContentAttributeTab) JSONObject
					.toBean(attrObj, BindContentAttributeTab.class);
			if (bindContent.getIntOrder() <= 0)
				continue;
			bindContent.setDatUpdateDatetime(date);
			bindContent.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
			bindContent.setIntViewContId(intViewContId);
			bindContentAttributeDao.save(bindContent);
		}
	}
	
	/**
	 * 保存或更新内容属性对应
	 * @param attribute
	 * @param viewId
	 * @author liuhj
	 * 2012-7-28下午02:48:06
	 */
	private void saveOrUpdContAttributeMapping(
			JSONArray attributes, int intViewContId) {
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		for (int i = 0; i < attributes.size(); i++) {
			JSONObject attrObj = JSONObject.fromObject(attributes.get(i));
			BindContentAttributeTab bindContent = (BindContentAttributeTab) JSONObject
					.toBean(attrObj, BindContentAttributeTab.class);
			if (bindContent.getIntBindContAttributeId() == -1
					&& bindContent.getIntOrder() > 0) {
				// 保存
				bindContent.setDatUpdateDatetime(date);
				bindContent.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
				bindContent.setIntViewContId(intViewContId);
				bindContentAttributeDao.save(bindContent);
				continue;
			}
			if (bindContent.getIntBindContAttributeId() > 0
					&& bindContent.getIntOrder() == -1) {
				// 删除
				StringBuffer hql = new StringBuffer("update BindContentAttributeTab b");
				hql.append(" set b.intDeleteSign=:intDeleteSign");
				hql.append(" where b.intBindContAttributeId=:intBindContAttributeId");
				HashMap<String, Object> args = new HashMap<String, Object>();
				args.put("intDeleteSign", GenericConstants.DELETE_SIGN_DELETED);
				args.put("intBindContAttributeId", bindContent.getIntBindContAttributeId());
				bindContentAttributeDao.hqlOperation(hql.toString(), args);
				continue;
			}
			if (bindContent.getIntBindContAttributeId() > 0
					&& bindContent.getIntOrder() != -1) {
				// 更新
				StringBuffer hql = new StringBuffer("update BindContentAttributeTab b");
				hql.append(" set b.intAttriId=:intAttriId,b.intOrder=:intOrder");
				hql.append(" where b.intBindContAttributeId=:intBindContAttributeId");
				HashMap<String, Object> args = new HashMap<String, Object>();
				args.put("intAttriId", bindContent.getIntAttriId());
				args.put("intOrder", bindContent.getIntOrder());
				args.put("intBindContAttributeId", bindContent.getIntBindContAttributeId());
				bindContentAttributeDao.hqlOperation(hql.toString(), args);
			}
		}
	}
	
	@Override
	@TriggersRemove(cacheName=GenericConstants.CATELOG_EHCACHE,removeAll=true)
	public void deleteContentBinding(int viewContId) {
		//删除视图内容关联
		appViewContentRalationDao.delete(viewContId);
		// 删除内容属性绑定
		StringBuffer hql = new StringBuffer("update BindContentAttributeTab b");
		hql.append(" set b.intDeleteSign=:intDeleteSign,b.datUpdateDatetime=:datUpdateDatetime");
		hql.append(" where b.intViewContId=:intViewContId");
		HashMap<String, Object> args = new HashMap<String, Object>();
		args.put("intDeleteSign", GenericConstants.DELETE_SIGN_DELETED);
		args.put("datUpdateDatetime", new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss").format(new Date()));
		args.put("intViewContId", viewContId);
		bindContentAttributeDao.hqlOperation(hql.toString(), args);
	}

	@Override
	@TriggersRemove(cacheName=GenericConstants.CATELOG_EHCACHE,removeAll=true)
	public void deleteContentView(int viewId) {
		List<AppViewContentRalationTab> relations = appViewContentRalationDao
			.getRelationsByViewId(viewId,new String[] {"intViewContId"});
		//删除视图
		appPageViewDao.delete(viewId);
		//删除视图内容绑定
		appViewContentRalationDao.deleteByViewId(viewId);
		StringBuffer ids = new StringBuffer("(");
		for (AppViewContentRalationTab appViewContentRalationTab : relations) {
			ids.append(appViewContentRalationTab.getIntViewContId()+",");
		}
		ids.deleteCharAt(ids.lastIndexOf(",")).append(",");
		//删除内容属性绑定
		StringBuffer hql = new StringBuffer("update BindContentAttributeTab b");
		hql.append(" set b.intDeleteSign=:intDeleteSign,b.datUpdateDatetime=:datUpdateDatetime");
		hql.append(" where b.intViewContId in" + ids);
		HashMap<String, Object> args = new HashMap<String, Object>();
		args.put("intDeleteSign", GenericConstants.DELETE_SIGN_DELETED);
		args.put("datUpdateDatetime", new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss").format(new Date()));
		bindContentAttributeDao.hqlOperation(hql.toString(), args);
	}

	@Override
	@TriggersRemove(cacheName=GenericConstants.CATELOG_EHCACHE,removeAll=true)
	public void saveOrUpdateMorePage(String jsonData, UserInfoDto user) {
		JSONObject json = JSONObject.fromObject(jsonData);
		if(log.isDebugEnabled()){
			log.debug("保存更多页面的json请求数据:"+json.toString());
		}
		//更新页面信息
		AppPageTab page = (AppPageTab) JSONObject.toBean(json
				.getJSONObject("pageInfo"), AppPageTab.class);
		updatePageTitleInfo(page,user);
		JSONArray ja = JSONArray.fromObject(json.get("views"));
		int size = ja.size();
		for (int i = 0; i < size; i++) {
			JSONObject jo = JSONObject.fromObject(ja.get(i));
			//遍历视图
			AppPageViewTab view = (AppPageViewTab) JSONObject.toBean(jo
					.getJSONObject("viewInfo"), AppPageViewTab.class);
			saveOrUpdateMoreBinding(jo, view, page, user);
		}
	}
	
	/**
	 * 保存或更新更多内容绑定
	 * @param jo
	 * @param view
	 * @param page
	 * @param user
	 * @author liuhj
	 * 2012-8-13下午03:09:42
	 */
	private void saveOrUpdateMoreBinding(JSONObject jo, AppPageViewTab view,
			AppPageTab page, UserInfoDto user) {
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		JSONArray contents = jo.getJSONArray("moreContents");
		if (contents == null || contents.size() <= 0){
			return ;
		}
		view.setDatUpdateDatetime(date);
		view.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		view.setIntViewBindDatatype(GenericConstants.BINDING_DATA_TYPE_FUNCTION);
		view.setVarViewConfig(jo.getJSONObject("viewInfo").getString("varViewConfig"));
		int viewId = view.getIntViewId();
		if (viewId == -1) {
			//保存视图
			view.setIntResourceId(page.getIntResourceId());
			viewId = appPageViewDao.save(view);
		} else {
			//更新视图
			appPageViewDao.update(view);
		}
		for (int i = 0; i < contents.size(); i++) {
			MoreContentTab moreContentTab;
			JSONObject more = JSONObject.fromObject(contents.get(i));
			int actiontype = more.getInt("intMoreActionType");
			if (actiontype == 18) {
				String varMoreName = more.getString("varMoreName");
				int intMoreContent = more.getInt("intMoreContent");
				// String varIconUrl = more.getString("varMoreName");
				int intIconId = more.getInt("intIconId");
				int intOrder = more.getInt("intOrder");
				String varMoreContent = more.get("varMoreContent").toString();
				moreContentTab = new MoreContentTab();
				moreContentTab.setIntMoreActionType(actiontype);
				moreContentTab.setVarMoreName(varMoreName);
				moreContentTab.setIntMoreContent(intMoreContent);
				moreContentTab.setIntIconId(intIconId);
				moreContentTab.setIntOrder(intOrder);
				moreContentTab.setVarMoreContent(varMoreContent);
			} else {
				moreContentTab = (MoreContentTab) JSONObject.toBean(
						JSONObject.fromObject(contents.get(i)),
						MoreContentTab.class);
			}
			if (moreContentTab.getIntMoreContent() == -1) {
				// 新增
				moreContentTab.setIntViewId(viewId);
				moreContentTab.setIntResourceId(page.getIntResourceId());
				moreContentTab.setIntIconId(moreContentTab.getIntIconId() == -1 ? 0
								: moreContentTab.getIntIconId());
				saveMoreContent(moreContentTab, user.getAppId());
			} else {
				updateMoreContent(moreContentTab);
			}
		}
	}
	
	/**
	 * 保存更多内容
	 * @param moreContentTab
	 * @param appId
	 * @return
	 * @author liuhj
	 * 2012-8-13下午02:12:00
	 */
	private Integer saveMoreContent(MoreContentTab moreContentTab, int appId) {
		moreContentTab.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		moreContentTab.setDatUpdateDatetime(new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss").format(new Date()));
		moreContentTab.setIntAppId(appId);
		Integer id = moreContentDao.save(moreContentTab);
		return id;
	}
	
	/**
	 * 更新更多内容
	 * @param moreContentTab
	 * @author liuhj
	 * 2012-8-13下午02:41:43
	 */
	private void updateMoreContent(MoreContentTab moreContentTab) {
		StringBuffer hql = new StringBuffer("update MoreContentTab m");
		HashMap<String, Object> args = new HashMap<String, Object>();
		hql.append(" set m.varMoreName=:varMoreName,m.varMoreContent=:varMoreContent");
		hql.append(",m.intMoreActionType=:intMoreActionType");
		hql.append(",m.datUpdateDatetime=:datUpdateDatetime");
		hql.append(",m.intIconId=:intIconId");
		hql.append(",m.intOrder=:intOrder");
		hql.append(" where m.intMoreContent=:intMoreContent");
		args.put("varMoreName", moreContentTab.getVarMoreName());
		args.put("datUpdateDatetime", new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss").format(new Date()));
		args.put("varMoreContent", moreContentTab.getVarMoreContent());
		args.put("intMoreActionType", moreContentTab.getIntMoreActionType());
		args.put("intMoreContent", moreContentTab.getIntMoreContent());
		args.put("intIconId", moreContentTab.getIntIconId() == -1 ? 0
				: moreContentTab.getIntIconId());
		args.put("intOrder", moreContentTab.getIntOrder());
		moreContentDao.hqlOperation(hql.toString(), args);
	}

	@Override
	public List<TypeDto> getMoreActionList(Integer appId) {
		boolean isHasProduct = false;
		boolean isHasActivity = false;
		List<CatelogTab> catelogs = catelogDao.getNextLevelChildren(appId,0,
				new String[] { "intCateId", "varCateName" });
		for (CatelogTab catelogTab : catelogs) {
			if ("产品".equals(catelogTab.getVarCateName().trim())) {
				isHasProduct = true;
			}
			if ("活动".equals(catelogTab.getVarCateName().trim())) {
				isHasActivity = true;
			}
		}
		return typeDao.getMoreTypeList(isHasProduct, isHasActivity);
	}

	@Override
	public List<AppPageTab> getCustomPages(Integer appId) {
		StringBuffer hql = new StringBuffer("select new AppPageTab(a.intResourceId,a.varTitleName)");
		hql.append(" from AppPageTab a");
		hql.append(" where a.intDeleteSign=:intDeleteSign");
		hql.append(" and a.intType=:intType");
		hql.append(" and a.intAppId=:intAppId");
		Map<String, Object> argsMap = new HashMap<String, Object>();
		argsMap.put("intDeleteSign", GenericConstants.DELETE_SIGN_EXIST);
		argsMap.put("intType", GenericConstants.OPTION_YES);
		argsMap.put("intAppId", appId);
		return appPageDao.hqlGetList(hql.toString(), argsMap);
	}

	@Override
	public String getCustomPageTree(String jsonData) {
		AppPageDto appPageDto = (AppPageDto) JSONObject.toBean(JSONObject.fromObject(jsonData),AppPageDto.class);
		List<AppPageDto> lstPages = new ArrayList<AppPageDto>();
		appPageDto.setIntNavigateType(0);
		lstPages.add(appPageDto);
		return populateTree(lstPages);
	}

	@Override
	public void deletePage(int pageId) {
		appPageDao.delete(pageId);
		List<AppPageViewTab> views = appPageViewDao.getViewsInfoByPageId(pageId, new String[] { "intViewId" }, false);
		for (AppPageViewTab appPageViewTab : views) {
			deleteView(appPageViewTab.getIntViewId());
		}
	}

}
